package com.itqf.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;


/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/3/12
 * @Time: 下午2:53
 */
@Component
public class RabbitMQMessageListener {

    @Resource
    private RedisTemplate<String,String> redisTemplate;


    public  RabbitMQMessageListener(){
        System.out.println("准备监听消息：");
    }


    @RabbitListener(queues="springboot-queue")
    public  void  onMessage(Message message, Channel channel){

        String id = message.getMessageProperties().getMessageId();
        String  messageId = redisTemplate.opsForValue().get("messageId");

        if (id!=null&&id.equals(messageId)){
            System.out.println("该消息已经消费过！！");
            return;
        }
        try {
            System.out.println("消费者接到消息："+new String(message.getBody()));
            System.out.println("业务逻辑处理完毕！！消息消费完毕");

            //每次消费完毕，把消息的id存储到redis中
            redisTemplate.opsForValue().set("messageId",id);
            int i = 10/0;//人为制造异常  网络波动
            //手动确认 DeliveryTag
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //拒绝确认
            try {
                /**
                 * 拒绝确认消息:<br>
                 * channel.basicNack(long deliveryTag, boolean multiple, boolean requeue) ; <br>
                 * deliveryTag:该消息的index<br>
                 * multiple：是否批量.true:将一次性拒绝所有小于deliveryTag的消息。<br>
                 * requeue：被拒绝的是否重新入队列 <br>
                 */
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }


}
